package com.ocean.core.util.wechat;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.ocean.core.exception.verify.ApplicationException;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付
 *
 * @author zhang
 * @since 2023/2/14
 */
public class WxPayNativesUtil {

    public static String requestPay(String orderSn, BigDecimal totalFee, String body, String back) {
        WXPay wxPay = new WXPay(new WxPayConfig());
        HashMap<String, String> data = new HashMap<>();
        data.put("body", body);
        data.put("out_trade_no", orderSn);
        data.put("fee_type", "CNY");
        data.put("total_fee", totalFee.multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
        data.put("trade_type", "NATIVE");
        data.put("notify_url", back);
        try {
            //通过data集合中的重要参数请求微信服务器，然后微信服务器将参数封装到resp中
            Map<String, String> resp = wxPay.unifiedOrder(data);
            //通过微信服务器返回的数据得到微信支付二维码，然后通过map集合返回给前端
            return resp.get("code_url");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //封装返回给前端的信息
        throw new ApplicationException("请求支付失败，请联系管理员");
    }

    public static Map<String, String> successCallback(HttpServletRequest request) throws Exception {
        //获取请求输入流
        ServletInputStream is = request.getInputStream();
        //设置每次读取的大小为1024字节
        byte[] bs = new byte[1024];
        int len = -1;
        //将流中信息封装到StringBuffer字符串中
        StringBuilder buffer = new StringBuilder();
        //循环读取
        while ((len = is.read(bs)) != -1) {
            buffer.append(new String(bs, 0, len));
        }
        String str = buffer.toString();
        //通过此方法将规范的字符串转化为map集合
        return WXPayUtil.xmlToMap(str);
    }
}
